package week_five;

public class KokoEatingBananas_875 {
    public int minEatingSpeed(int[] piles, int h) {
        int l = 1, r = 1000000000;
        while (l < r) {
            int mid = (l + r) / 2;
            if (isValidK(piles, h, mid)) r = mid;
            else l = mid + 1;
        }
        return l;
    }

    private boolean isValidK(int[] piles, int h, int K) {
        int hours = 0;

        for (int i = 0; i < piles.length; i++) {
            //向上取整，整除的时候不需要+1.
            if (piles[i] % K == 0)
                hours += piles[i] / K;
            else
                hours += ((int) piles[i] / K + 1);
        }
        // System.out.println("mid: "+K+" hours: "+ hours);
        return hours <= h;
    }
}
